package com.xiaocz.hblsubstitutedriving;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.annotation.NonNull;
import android.support.multidex.MultiDex;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreater;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.vise.log.ViseLog;
import com.vise.log.inner.LogcatTree;
import com.xiaocz.common.Common;
import com.xiaocz.common.app.Application;
import com.xiaocz.common.http.AsyncHttpPostFormData;
import com.xiaocz.common.http.AsyncHttpResponse;
import com.xiaocz.common.http.AsyncOkHttpClient;
import com.xiaocz.common.http.AsyncResponseHandler;
import com.xiaocz.common.model.RspModel;
import com.xiaocz.common.utils.AccountManagers;
import com.xiaocz.common.utils.ToastUtil;
import com.xiaocz.common.widgets.load.LoadFactory;
import com.xiaocz.hblsubstitutedriving.base.AppFrontBackHelper;
import com.xiaocz.hblsubstitutedriving.model.CloudOrder;
import com.xiaocz.hblsubstitutedriving.utils.AudioFocusManager;
import com.xiaocz.hblsubstitutedriving.utils.Constants;
import com.xiaocz.hblsubstitutedriving.utils.CrashHandler;
import com.xiaocz.hblsubstitutedriving.widget.EmptyView;
import com.xiaocz.hblsubstitutedriving.widget.ErrorView;
import com.xiaocz.hblsubstitutedriving.widget.LoadingView;
import com.xiaocz.hblsubstitutedriving.widget.NetErrorView;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

public class App extends Application {
    private int count = 0;
    public static Context context;
    private static App instance = new App();
    public static IWXAPI mWxApi;
    public AudioFocusManager audioFocusManager;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        audioFocusManager = new AudioFocusManager();
        LoadFactory.getInstance()
                .addView(new LoadingView())
                .addView(new EmptyView())
                .addView(new ErrorView())
                .addView(new NetErrorView())
                .setDefaultViewClass(LoadingView.class);
        MultiDex.install(this);
        infoViseLog();
        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(this);
        crashHandler.readTxt();
        //微信授权boss hugo hbxw-025
        registToWX();
        // 下拉刷新控件
        SmartRefreshLayout.setDefaultRefreshHeaderCreater(new DefaultRefreshHeaderCreater() {
            @NonNull
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.windowsBackground, R.color.textColorAccent); //全局设置主题颜色
                //指定为经典Header，默认是 贝塞尔雷达Header
                return new ClassicsHeader(context).setSpinnerStyle(SpinnerStyle.Scale);
            }
        });
        // 初始化SDK
        UMConfigure.init(this, "5f044e7ddbc2ec083e66ed56", "ZIR", UMConfigure.DEVICE_TYPE_PHONE, null);
        // 选用AUTO页面采集模式
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO);
        //initBackgroundCallBack();
    }

    private long mExitTime;//离开前台时长

    private void initBackgroundCallBack() {
        AppFrontBackHelper helper = new AppFrontBackHelper();
        helper.register(App.this, new AppFrontBackHelper.OnAppStatusListener() {
            @Override
            public void onFront(Activity activity) {
                //应用从后台回到前台 需要做的操作
                getNewOrder();
            }

            @Override
            public void onBack() {
                //应用切到后台处理(重新计时)
                mExitTime = System.currentTimeMillis();
            }
        });
    }

    /**
     * 音频焦点
     * isListener 是否需要本方法监听焦点
     */
    public MediaPlayer audioFocus(final int res, boolean isListener) {
        if (audioFocusManager == null) {
            audioFocusManager = new AudioFocusManager();
        }
        getPlayMusic(res, isListener);
        //请求语音播放焦点
        int requestCode = audioFocusManager.requestTheAudioFocus(context, new AudioFocusManager.AudioListener() {
            @Override
            public void start() {
                mediaPlayer.start();
            }

            @Override
            public void pause() {
                mediaPlayer.pause();
            }
        });
        if (requestCode == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            mediaPlayer.start();
        }
        return mediaPlayer;
    }

    public MediaPlayer mediaPlayer;

    /**
     * 播放音乐文件
     */
    public void getPlayMusic(int res, boolean isListener) {
        mediaPlayer = MediaPlayer.create(context.getApplicationContext(), res);
        if (isListener) {
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    if (audioFocusManager != null) {
                        audioFocusManager.releaseTheAudioFocus();
                        try {
                            if (mediaPlayer != null) {
                                if (mediaPlayer.isPlaying()) {
                                    mediaPlayer.stop();
                                }
                                mediaPlayer.release();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
    }

    /**
     * 判断app是否在后台
     */
    public boolean isBackground() {
        if (count <= 0) {
            return true;
        } else {
            return false;
        }
    }


    private void registToWX() {
        //AppConst.WEIXIN.APP_ID是指你应用在微信开放平台上的AppID，记得替换。
        mWxApi = WXAPIFactory.createWXAPI(this, Common.APP_ID, false);
        // 将该app注册到微信
        mWxApi.registerApp(Common.APP_ID);
    }

    public static App getInstance() {
        return instance;
    }

//    private void initCrash() {
//        CaocConfig.Builder.create()
//                .backgroundMode(CaocConfig.BACKGROUND_MODE_SILENT) //背景模式,开启沉浸式
//                .enabled(false) //是否启动全局异常捕获
//                .showErrorDetails(true) //是否显示错误详细信息
//                .showRestartButton(true) //是否显示重启按钮
//                .trackActivities(true) //是否跟踪Activity
//                .minTimeBetweenCrashesMs(2000) //崩溃的间隔时间(毫秒)
//                .errorDrawable(R.mipmap.ic_launcher) //错误图标重新启动后的activity
////                .restartActivity(LoginActivity.class) //
////                .errorActivity(DefaultErrorActivity.class) //崩溃后的错误activity
//////                .eventListener(new CustomActivityOnCrash.EventListener() {
//////                    @Override
//////                    public void onLaunchErrorActivity() {
//////
//////                    }
//////
//////                    @Override
//////                    public void onRestartAppFromErrorActivity() {
////
////                    }
////
////                    @Override
////                    public void onCloseAppFromErrorActivity() {
////
////                    }
////                }) //崩溃后的错误监听
//                .apply();
//    }

    /**
     * 日志打印
     */
    private void infoViseLog() {
        ViseLog.getLogConfig()
                .configAllowLog(Common.Constant.testing)//是否输出日志
                .configShowBorders(false)//是否排版显示
                .configTagPrefix("ViseLog")//设置标签前缀
                //.configFormatTag("%d{HH:mm:ss:SSS} %t %c{-5}")//个性化设置标签，默认显示包名
                .configLevel(Log.VERBOSE);//设置日志最小输出级别，默认Log.VERBOSE
        ViseLog.plant(new LogcatTree());//添加打印日志信息到Logcat的树
    }

    public void showMessage() {
        showMessage(context.getResources().getString(R.string.toast_none), Toast.LENGTH_SHORT);
    }

    public void showMessage(String message) {
        showMessage(message, Toast.LENGTH_SHORT);
    }

    public void showMessage(String message, int duration) {
        ToastUtil.getInstance()
                .setBackgroundColor(context.getResources().getColor(R.color.colorAccent))
                .setTextColor(context.getResources().getColor(R.color.textColorLight))
                .show(message, duration);
    }


    /**
     * 获取最新订单
     */
    private void getNewOrder() {
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        if (Constants.getLocation() == null) {
            return;
        }
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        asyncHttpPostFormData.addFormData("driver_lat", Constants.getLocation().getLatitude());
        asyncHttpPostFormData.addFormData("driver_lng", Constants.getLocation().getLongitude());
        okHttpClient.post(Common.Constant.API_IP + "api/Driver/queryDriverTuiSongOrder", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                Type type = new TypeToken<RspModel<List<CloudOrder>>>() {
                }.getType();
                RspModel<List<CloudOrder>> rspModel = getAnalysis(response, type, "获取最新订单");
                if (rspModel == null) {
                    return;
                }
                if (rspModel.getCode() == 200) {
                    if (rspModel.getData() != null && !"[]".equals(rspModel.getData().toString())) {
                        List<CloudOrder> orderList = rspModel.getData();
                        int time = 0, max = 0;
                        for (int i = 0; i < orderList.size(); i++) {
                            if (orderList.get(i).getT() > time) {
                                time = orderList.get(i).getT();
                                max = i;
                            }
                        }
                    }
                }
            }
        });
    }

    public <T> RspModel<T> getAnalysis(AsyncHttpResponse response, Type type, String log) {
        ViseLog.d(getClass().getSimpleName() + ":" + response.toString());
        switch (response.getCode()) {
            case 200:
                try {
                    RspModel<T> rspModel = new Gson().fromJson(response.getBody(), type);
                    ViseLog.e(log + rspModel.toString());
                    return rspModel;
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
                break;
            default:
                App.getInstance().showMessage(getString(R.string.service_error));
                break;
        }
        return null;
    }
}
